<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
<style>
div{width:50px; height:50px; background-color:red;}
</style>
<script>
window.onload = function(){
    var str='';
    var len = 16;
    var timer = null;
    var finished = true;
    var flag = true;	//代表方向
    
    for(i=0;i<len;i++){
        str += '<div style="position:absolute;top:20px;left:'+(70*i+20)+'px"></div>';    //后面的运算需要注意+和''的位置
    }
    document.body.innerHTML = str;
    var aDiv = document.getElementsByTagName('div');

    document.onclick = function (){
    	if (!finished) {return};
    	finished = false;

    	var num = 0;
	    clearInterval(timer);
	    timer = setInterval(function(){				//外边的定时器包着里面的设有定时器的函数【定时器包着定时器】
	    	
	    	doMove(aDiv[num],'top',20,flag?500:20,num == len -1 ? function (){
	    		finished = true;		//最里边的定时器里边判断最后一个div是否完成
	    		flag = !flag;
	    		alert('最后一个div结束，可以再点击了')
	    	} : null);

	    	num ++;
	    	if ( num == len ) {
	    		clearInterval(timer);	//不在外边的定时器里边判断，因为外面的定时器结束时（即num==len时），最后几个div其实还没有开始动
	    	};
	    },50)
	}
}

function getStyle(obj,attr){
	return obj.currentStyle ? obj.currentStyle[attr] : getComputedStyle(obj)[attr];
}

function doMove(obj, attr, dir, target, endFn){
	clearInterval(obj.timer);
	dir = parseInt(getStyle(obj,attr)) < target ? dir : -dir;

	obj.timer = setInterval(function (){
		var speed = parseInt(getStyle(obj,attr)) + dir;
		if (speed > target && dir > 0 | speed < target && dir < 0) {
			speed = target;
		};
		obj.style[attr] = speed + 'px';
		if (speed == target) {
			clearInterval(obj.timer);
			endFn && endFn();
		};
	},20)
}
</script>
</head>
<body>
	
</body>
</html>